<?php
namespace app\admin\model;
use think\Model;
use think\Validate;
class Article extends Model
{
    //钩子函数
     protected static function init()
    {
        Article::event('before_insert', function ($data) {
            	if($_FILES['thumb']['tmp_name']){
                // 获取表单上传文件 例如上传了001.jpg
                $file = request()->file('thumb');
                // 验证后移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                 $thumb='/bike/'. 'public' . DS . 'uploads'.'/'.$info->getSaveName();
                 $data['thumb']=$thumb;
                }else{
                    // 上传失败获取错误信息
                    return  $file->getError();
                }
            }
        });

        Article::event('before_update', function ($data) {

                    $arts=Article::get($data->id);

                    if($arts->thumb){
                       $thumbpath= $_SERVER['DOCUMENT_ROOT'].$arts->thumb;
                       unlink($thumbpath);
                    }
                
                if($_FILES['thumb']['tmp_name']){
                // 获取表单上传文件 例如上传了001.jpg
                $file = request()->file('thumb');
                // 验证后移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                 $thumb='/bike/'. 'public' . DS . 'uploads'.'/'.$info->getSaveName();
                 $data['thumb']=$thumb;
                }else{
                    // 上传失败获取错误信息
                    return  $file->getError();
                }
            }
            
        });


        Article::event('before_delete', function ($data) {
                    //删除图片
                    $arts=Article::get($data->id);
                 $thumbpath= $_SERVER['DOCUMENT_ROOT'].$arts->thumb;
                    if($arts->thumb){
                       unlink($thumbpath);
                    }
            
        });

    }
}



